using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Box2D.XNA;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Elementum
{
    class Monster : Actor
    {
        Body _rightSensor, _leftSensor,_buttomSensor;
        Body _rightSensorContactBody, _leftSensorContactBody;
        Animation _sprite,_spriteSleep;
        Animation lm,rm,bm;
        bool _isRightContact, _isLeftContact,_isSleep,_isButtomContact;
        public  Item _item;
        public Vector2 SPEED = new Vector2(1.5f, 0);
        public Vector2 _speed;

       
        protected override void ConfigFilter()
        {
            base.ConfigFilter();
            _filter.categoryBits = MonsterCategory;
            _filter.maskBits = MonsterMask;
        }

        public Monster(Stage stage)
            : base(stage.World, stage)
        {
            _body.SetUserData("monster");
            _sprite = new Animation("images/monster/monster", new Rectangle(0, 0, 120, 33), new Point(40, 33));
            _sprite.DeltaTime = 80;
            _sprite.LayerDepth = 0.8f;
            _spriteSleep = new Animation("images/monster/monster", new Rectangle(120, 0, 40, 33), new Point(40, 33));
            
            _spriteSleep.LayerDepth = 0.8f;
            CurrentAnimation = _sprite;
            Size = new Vector2(30, 30);
            IsSleep = false;
            Speed = SPEED;
           // _contactDetector = new PlayerCollisionDetector(_body);
            //_body.BeginContact += _contactDetector.BeginContact;
            //_body.BeginContact += _contactDetector.EndContact;
            _body.SetType(BodyType.Dynamic);
            _body.SetFixedRotation(true);

            lm=new Animation("images/mySprite",new Point((int)_size.X/4,(int)_size.Y/5));
            rm = new Animation("images/system/black", new Point((int)_size.X / 4, (int)_size.Y / 5));
            bm = new Animation("images/system/black", new Point((int)(_size.X /3f), (int)_size.Y / 4));
        }

        public override void CreatBody(World world)
        {
            base.CreatBody(world);
            BodyDef bd = new BodyDef();
            bd.type = BodyType.Dynamic;
            bd.fixedRotation = true;

            _rightSensor = _world.CreateBody(bd);
            _rightSensor.SetUserData("MRS");
            _rightSensor.BeginContact += RightSensorBeginContact;
            _rightSensor.EndContact += RightSensorEndContact;
            _buttomSensor = _world.CreateBody(bd);
            _leftSensor = _world.CreateBody(bd);
            _leftSensor.SetUserData("MLS");
            _leftSensor.BeginContact += LeftSensorBeginContact;
            _leftSensor.EndContact += LeftSensorEndContact;
            _buttomSensor.BeginContact += ButtomSensorBeginContact;
            _buttomSensor.EndContact += ButtomSensorEndContact;
        }



        protected override void SetSize(Vector2 size)
        {
            _size = size;
            float _radius = _size.X / (2 * PIXEL_TO_METER);
            if (_fixture == null)
            {
                FixtureDef f = new FixtureDef();
                CircleShape c = new CircleShape();
                //PolygonShape p0 = new PolygonShape();
                //p0.SetAsBox((_size.X-2) / (PIXEL_TO_METER * 2), (_size.X-2) / (PIXEL_TO_METER * 2));
                f.shape = c;
                f.density = 200;
                f.restitution = 0f;
                f.friction = 0.25f;
                c._radius = _radius;
                this._fixture = _body.CreateFixture(f);
                _fixture.SetFilterData(ref _filter);
                //f.shape = p0;
                //this._fixture = _body.CreateFixture(f);
                //_fixture.SetFilterData(ref _filter);
            }
            FixtureDef fd = new FixtureDef();
            fd.isSensor = true;
            fd.density = 0;
            PolygonShape p = new PolygonShape();
            p.SetAsBox(_size.X / (PIXEL_TO_METER * 4), _size.Y / (PIXEL_TO_METER * 5));
            fd.shape = p;
            _leftSensor.CreateFixture(fd);
            _rightSensor.CreateFixture(fd);
            p.SetAsBox(_size.X / (PIXEL_TO_METER * 3f), _size.Y / (PIXEL_TO_METER * 4f));
            _buttomSensor.CreateFixture(fd);
            _fixture.SetFilterData(ref _filter);
        }

        public void ButtomSensorBeginContact(Contact contact, Body contactBody, float normal)
        {
            if (contactBody.GetUserData() == "ground" || contactBody.GetUserData() == "door")
            {
                buttonList.Add(contactBody);
            }
        }
        public List<Body> buttonList = new List<Body>();
        public void ButtomSensorEndContact(Contact contact, Body contactBody, float normal)
        {
            if (contactBody.GetUserData() == "ground" || contactBody.GetUserData() == "door")
            {
                buttonList.Remove(contactBody);
            }
        }

        public Vector2 Speed
        {
            set
            {
                _speed = value;
                if (_speed.X > 0)//r
                    CurrentAnimation.DrawEffect = SpriteEffects.FlipHorizontally;
                else//l
                    CurrentAnimation.DrawEffect = SpriteEffects.None;
            }
            get { return _speed; }
        }

        public bool IsSleep
        {
            get { return _isSleep; }
            set
            {
                _isSleep = value;
                if (value)
                {
                    CurrentAnimation = _spriteSleep;
                    // UpDateAction += slp;
                    if (_item != null)
                    {
                        _item.UpDateAction += _item.ThrowOutItem;
                        _item = null;
                    }
                }
                else
                {
                    // UpDateAction += aslp;
                    CurrentAnimation = _sprite;
                }
            }
        }

        public override void Update(int delta)
        {
            base.Update(delta);

            if (_isRightContact && !_isLeftContact)
                Speed = SPEED;
            if (!_isRightContact && _isLeftContact)
                Speed = -SPEED;

            //_rightSensorContactBody.

            _rightSensor.SetTransform(_body.Position + new Vector2(_size.X / PIXEL_TO_METER, -_size.Y / PIXEL_TO_METER/1.1f),0);
            _leftSensor.SetTransform(_body.Position + new Vector2(-_size.X / PIXEL_TO_METER, -_size.Y / PIXEL_TO_METER / 1.1f), 0);
            _buttomSensor.Position = _body.Position + new Vector2(0, -_size.Y / PIXEL_TO_METER / 2);

          //  PlayerCollisionDetector con = (PlayerCollisionDetector)_contactDetector;
            
            if(!IsSleep&&buttonList.Count()!=0)
            _body.SetLinearVelocity(new Vector2(Speed.X,_body.GetLinearVelocity().Y));
            else
                _body.SetLinearVelocity(new Vector2(0, _body.GetLinearVelocity().Y));

        }
        
        public override void OnDraw(SpriteBatch spriteBatch, Matrix transform)
        {
            base.OnDraw(spriteBatch, transform);
            PlayerCollisionDetector con = (PlayerCollisionDetector)_contactDetector;
            lm.LayerDepth = 0;
            rm.LayerDepth = 0;
            bm.LayerDepth = 0;
            //lm.OnDraw(spriteBatch, new Vector2(500,200), transform);
            //rm.OnDraw(spriteBatch, new Vector2(0, 480) - (_rightSensor.Position * PIXEL_TO_METER), transform);
            //lm.OnDraw(spriteBatch, new Vector2((_leftSensor.Position.X * PIXEL_TO_METER), (480 - _leftSensor.Position.Y * PIXEL_TO_METER)), transform);
            //rm.OnDraw(spriteBatch, new Vector2((_rightSensor.Position.X * PIXEL_TO_METER), (480 - _rightSensor.Position.Y * PIXEL_TO_METER)), transform);
            //bm.OnDraw(spriteBatch, new Vector2((_buttomSensor.Position.X * PIXEL_TO_METER), (480 - _buttomSensor.Position.Y * PIXEL_TO_METER)), transform);
            //spriteBatch.DrawString(Stage.Font, "body" + (new Vector2(0, 480) - (_body.Position * PIXEL_TO_METER)), new Vector2(700, 180), Color.White);
            //spriteBatch.DrawString(Stage.Font, "_leftSensor" + _isLeftContact, new Vector2(700, 200), Color.White);
            //spriteBatch.DrawString(Stage.Font, "_rightSensor" + _isRightContact, new Vector2(700, 220), Color.White);
            //if (_rightSensorContactBody != null)
            //    spriteBatch.DrawString(Stage.Font, "" + _rightSensorContactBody.GetUserData(), new Vector2(700 , 320), Color.White);
            //if (_leftSensorContactBody != null)
            //    spriteBatch.DrawString(Stage.Font, "" + _leftSensorContactBody.GetUserData(), new Vector2(700, 300), Color.White);

            //spriteBatch.DrawString(Stage.Font, "_leftSensor" + (new Vector2(0, 480) - (_leftSensor.Position * PIXEL_TO_METER)), new Vector2(700, 200), Color.White);
            //spriteBatch.DrawString(Stage.Font, "_rightSensor" + (new Vector2(0, 480) - (_rightSensor.Position * PIXEL_TO_METER)), new Vector2(700, 220), Color.White);
            //spriteBatch.DrawString(Stage.Font, "buttonList.Count()" + buttonList.Count(), new Vector2(700, 240), Color.White);

        }

        public void RightSensorBeginContact(Contact contact, Body contactBody, float normal) {
            if (contactBody.GetUserData() == "ground" || contactBody.GetUserData() == "door")
            {
                _rightSensorContactBody = contactBody;
                _isRightContact = true;
            }
        }

        public void LeftSensorBeginContact(Contact contact, Body contactBody, float normal) {
            if (contactBody.GetUserData() == "ground" || contactBody.GetUserData() == "door")
            {
                _leftSensorContactBody = contactBody;
                _isLeftContact = true;
            }
        }

        public void RightSensorEndContact(Contact contact, Body contactBody, float normal)
        {
            if (contactBody==_rightSensorContactBody) {
                
                _isRightContact = false;
            }
        }

        public void LeftSensorEndContact(Contact contact, Body contactBody, float normal)
        {
            if (contactBody==_leftSensorContactBody)
            {
                
                _isLeftContact = false;
            }
        }

        public override void BeginContactAction(Contact contact, Body contactBody, float normal)
        {
            base.BeginContactAction(contact, contactBody, normal);
            if (contactBody._userData == "ground" || contactBody._userData == "door" || contactBody._userData == "killBund")
            {
                if (normal > 315 || normal < 45)//right
                {
                    //_rightSensorContactBody = null;
                    //_isRightContact = true;
                    Speed = -SPEED;
                }

                if (normal > 135 && normal < 225)//left
                {
                    //_leftSensorContactBody = null;
                    //_isLeftContact = true;
                    Speed = SPEED;
                }
            }

            if (contactBody._userData == "player") {
                if (normal > 225 && normal < 315)//up
                    IsSleep = !IsSleep;
                else if(!IsSleep){
                    Player player = (Player)contactBody.Owner;
                    player.KillPlayer();
                   // _speed = -_speed;
                }
                

            }

        }


        public override void EndContactAction(Contact contact, Body contactBody, float normal)
        {
            base.EndContactAction(contact, contactBody, normal);
        }

    }




}
